﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using App.Common;
using QxFramework.Core;
using DG.Tweening;
public class Player : MonoBase
{
    public int PlayerID;
    private Transform Mana;
    private bool canMoveUp;
    private bool canMoveDown;
    private bool canMoveLeft;
    private bool canMoveRight;
    public override void Awake()
    {
        base.Awake();
        Mana = transform.Find("Sprite/Mana");
    }
    public override void Update()
    {
        base.Update();
        CheckWall();
        PlayerControl();
        ManaAnimation();
        //ColorControl();

    }
    public override void OnEnable()
    {
        base.OnEnable();
        StartCoroutine(InitUI());
    }
    IEnumerator InitUI()
    {
        yield return 0;
        PlayerID = int.Parse((name.Split('-')[1]).Split('_')[0]);
        UIManager.Instance.Open("MainUI", 0, args: PlayerID);
        UIManager.Instance.Open("TargetUI", 3, args: PlayerID);
    }

    private void Start()
    {
        canMoveUp = true;
        canMoveDown = true;
        canMoveLeft = true;
        canMoveRight = true;
    }

    public override void LateUpdate()
    {
        base.LateUpdate();
        CheckChangeAttr();
        GameMgr.Get<IMonoManager>().GetMono(gameObject.name).Attr = monoBase.Attr;
        SetMagicCircle(monoBase.Attr);
    }
    MapEditorBase.MapGround LastFloor;
    public void ChackFloorState()
    {
        if (LastFloor != null)
        {
            if (LastFloor != GetNowGround())
            {
                LastFloor.IsPlayerIn = false;
            }
        }
        LastFloor = GetNowGround();
        GetNowGround().IsPlayerIn = true;
    }
    //改变属性
    public void CheckChangeAttr()
    {
        ChackFloorState();
        if (InputManager.Instance.Port(PlayerID))
        {
            if (GetNowGround().attr != MonoAttribute.None)
            {
                monoBase.Attr = GetNowGround().attr;
                GetNowGround().attr = MonoAttribute.None;
                ATimer = monoBase.buffStatus.AttrLastTime; ;
            }
        }
        AttrTimer();
    }
    float ATimer;
    public void AttrTimer()
    {
        if (!ItsYourTurn())
        {
            return;
        }
        if (!GameMgr.Get<ITimeManager>().IsTimeGoing())
        {
            return;
        }

        if (monoBase.Attr != MonoAttribute.None)
        {
            
            ATimer -= Time.deltaTime;
            if (ATimer < 0)
            {
                monoBase.Attr = MonoAttribute.None;
            }
        }
        else
        {
            ATimer = monoBase.buffStatus.AttrLastTime; 
        }
        IsFlashing = (ATimer < Data.Instance.TableAgent.GetInt("Base", "AttrWarningTime", "Value"));
        FlashingCircle();
    }
    float Alph = 1.0f;
    float AlphPlus = 0.1f;
    bool IsFlashing = true;
    private void FlashingCircle()
    {
        if (Alph >= 1)
        {
            Alph = 1;

            AlphPlus = (IsFlashing) ? -0.1f : 0f;
        }
        if (Alph < 0)
        {
            Alph = 0;
            AlphPlus = 0.1f;
        }
        Alph += AlphPlus;
    }

    private void CheckWall()
    {
    }

    private void SetMagicCircle(MonoAttribute attr)
    {
        string name = attr.ToString();
        string[] attributes = { "Fire", "Dark", "Ice", "Shine", "Steam", "Electric", "Oil", "None" };
        Transform obj = gameObject.transform.Find("AttrCircle");
        for(int i =0;i<8;i++)
        {
            obj.Find(attributes[i]).gameObject.SetActive(attributes[i] == name);
            Color col = obj.Find(attributes[i]).GetComponent<SpriteRenderer>().color;
            col.a = Alph;
            obj.Find(attributes[i]).GetComponent<SpriteRenderer>().color = col;
        }
    }
    private void ManaAnimation()
    {
        foreach (Transform child in Mana.transform)
        {
            var emission = child.GetComponent<ParticleSystem>().emission;
            emission.enabled = (child.gameObject.name.Contains("Mana_"+ GameMgr.Get<IMonoManager>().CurrentAttrName(monoBase.Attr)));
        }
        if (InputManager.Instance.AttackAxis(PlayerID))
        {
            Mana.transform.position = transform.position + (InputManager.Instance.GetTarget(PlayerID) - monoBase.Position).normalized * 1.25f;
        }
    }
    private void PlayerControl()
    {
        if (!GameMgr.Get<IBattleManager>().GetBattleData().InBattle)
        {
            GameMgr.Get<ICameraManager>().SetPlayerMono(gameObject.name);
        }

        if (!ItsYourTurn())
        {
            return;
        }

        GameMgr.Get<ICameraManager>().SetBatlleMono(gameObject.name);

        if (InputManager.Instance.ClickFire(out Vector3 pos, PlayerID))
        {
            UseSkillJudge((pos - monoBase.Position).normalized, GameMgr.Get<IPlayerDataManager>().GetPlayerDatas().PlayerDatas[PlayerID].CurrentSkillID);
        }

        if (InputManager.Instance.ClickRoll(out Vector3 pos1, PlayerID))
        {
            if (UseLPJudge(-4000))
            {
                Vector3 P = (pos1 - monoBase.Position).normalized;
                monoBase.Direction = P;
                JudgeAnimDirect(monoBase.Direction);
                monoBase.monoRealtimeStatus.IsInvincible = true;
                GetComponentInChildren<AnimationUtil>().SetTrigger("Flashing", () =>
                {
                });
                LastTimeMove(P, (monoBase.Speed / FreezeRate) * 3, 15, () =>
                {
                    monoBase.monoRealtimeStatus.IsInvincible = false;
                });
            }
        }

        if (InputManager.Instance.ClickFight(out Vector3 pos2, PlayerID))
        {
            if (UseLPJudge(-2000))
            {
                Vector3 Direct = (pos2 - monoBase.Position).normalized;
                monoBase.Direction = Direct;
                JudgeAnimDirect(Direct);
                monoBase.monoRealtimeStatus.IsCounterAttack = true;
                StartCoroutine(CollChange(Direct));
                GetComponentInChildren<Animator>().enabled = false;
                transform.Find("Sprite").DOLocalMove(Direct.normalized * 0.9f, 0.15f).OnComplete(() =>
                {
                    transform.Find("Sprite").DOLocalMove(Vector3.zero, 0.1f).OnComplete(() =>
                    {
                        monoBase.monoRealtimeStatus.IsCounterAttack = false;
                        GetComponentInChildren<Animator>().enabled = true;
                    });
                    GetComponent<CircleCollider2D>().offset = Vector2.zero;
                    GetComponent<CircleCollider2D>().radius = 0.5f;
                });
                GameMgr.Get<ISkillManager>().BulletSkillAffect(monoBase, "FightBall", monoBase.Position, Direct, GetComponent<CircleCollider2D>().radius + 0.1f, monoBase.Attr,99);
            }
        }

        IEnumerator CollChange(Vector3 Direct)
        {
            GetComponent<CircleCollider2D>().offset += new Vector2(Direct.normalized.x, Direct.normalized.y) * 0.6f;
            GetComponent<CircleCollider2D>().radius += 0.08f;
            yield return 0;
            yield return 0;
            GetComponent<CircleCollider2D>().offset += new Vector2(Direct.normalized.x, Direct.normalized.y) * 0.8f;
            GetComponent<CircleCollider2D>().radius += 0.18f;
            yield return 0;
            GetComponent<CircleCollider2D>().offset -= new Vector2(Direct.normalized.x, Direct.normalized.y) * 0.2f;
            GetComponent<CircleCollider2D>().radius += 0.2f;
            yield return 0;
            GetComponent<CircleCollider2D>().offset -= new Vector2(Direct.normalized.x, Direct.normalized.y) * 0.2f;
            GetComponent<CircleCollider2D>().radius += 0.2f;
        }

        if (InputManager.Instance.Up(PlayerID))
        {
            if (canMoveUp)
            {
                monoBase.Direction = new Vector3(0, 1, 0);
                GetComponentInChildren<Animator>().SetFloat("Blend", 0f);
                GetComponentInChildren<Animator>().SetBool("Walking", true);
                if (InputManager.Instance.Left(PlayerID))
                {
                    if (canMoveLeft)
                        monoBase.Direction = new Vector3(-0.707f, 0.707f, 0);

                }
                else if (InputManager.Instance.Right(PlayerID))
                {
                    if (canMoveRight)
                        monoBase.Direction = new Vector3(0.707f, 0.707f, 0);
                }
                MoveByDirection(monoBase.Direction, monoBase.Speed);
            }
            else
                IfInputLR();
        }
        else if (InputManager.Instance.Down(PlayerID))
        {
            if(canMoveDown)
            {
                monoBase.Direction = new Vector3(0, -1, 0);
                GetComponentInChildren<Animator>().SetFloat("Blend", 0.33f);
                GetComponentInChildren<Animator>().SetBool("Walking", true);
                if (InputManager.Instance.Left(PlayerID))
                {
                    if (canMoveLeft)
                        monoBase.Direction = new Vector3(-0.707f, -0.707f, 0);
                }
                else if (InputManager.Instance.Right(PlayerID))
                {
                    if (canMoveRight)
                        monoBase.Direction = new Vector3(0.707f, -0.707f, 0);
                }
                MoveByDirection(monoBase.Direction, monoBase.Speed);
            }
            else
                IfInputLR();
        }
        else if (InputManager.Instance.Left(PlayerID))
        {
            if(canMoveLeft)
            {
                monoBase.Direction = new Vector3(-1, 0, 0);
                MoveByDirection(monoBase.Direction, monoBase.Speed);
                GetComponentInChildren<Animator>().SetFloat("Blend", 0.66f);
                GetComponentInChildren<Animator>().SetBool("Walking", true);
            }
            else
                IfInputUD();
        }
        else if (InputManager.Instance.Right(PlayerID))
        {
            if(canMoveRight)
            {
                monoBase.Direction = new Vector3(1, 0, 0);
                MoveByDirection(monoBase.Direction, monoBase.Speed);
                GetComponentInChildren<Animator>().SetFloat("Blend", 1f);
                GetComponentInChildren<Animator>().SetBool("Walking", true);
            }
            else
                IfInputUD();
        }
        else
        {
            GetComponentInChildren<Animator>().SetBool("Walking", false);
        }
        if (InputManager.Instance.NextSkill(PlayerID))
        {
            GameMgr.Get<IPlayerDataManager>().ChangeSkillID(GameMgr.Get<IPlayerDataManager>().GetPlayerDatas().PlayerDatas[PlayerID], true);
        }
        if (InputManager.Instance.PreviousSkill(PlayerID))
        {
            GameMgr.Get<IPlayerDataManager>().ChangeSkillID(GameMgr.Get<IPlayerDataManager>().GetPlayerDatas().PlayerDatas[PlayerID], false);
        }
        if (InputManager.Instance.Cheat)
        {
            GameMgr.Get<IMonoManager>().Cheat();
        }

        if (WithInRage(MonoBase.MonoTag.Enemy, 1f, out bool lostTarget1, out Vector3 otherDirect1, out GameObject Obj1))
        {
            if (lostTarget1)
            {
                return;
            }
            MoveByDirection(-otherDirect1, monoBase.Speed);
        }
        if (WithInRage(MonoBase.MonoTag.Player, 1f, out bool lostTarget2, out Vector3 otherDirect2, out GameObject Obj2))
        {
            if (lostTarget2)
            {
                return;
            }
            MoveByDirection(-otherDirect2, monoBase.Speed);
        }

    }
    public void SetCanMoveDirection(canMoveDir dir, bool canMove)
    {
        switch (dir)
        {
            case canMoveDir.Above:
                canMoveUp = canMove;
                break;
            case canMoveDir.Below:
                canMoveDown = canMove;
                break;
            case canMoveDir.Left:
                canMoveLeft = canMove;
                break;
            case canMoveDir.Right:
                canMoveRight = canMove;
                break;
        }
    }
    public bool GetCanMoveDirection(canMoveDir dir)
    {
        switch (dir)
        {
            case canMoveDir.Above:
                return canMoveUp;
            case canMoveDir.Below:
                return canMoveDown;
            case canMoveDir.Left:
                return canMoveLeft;
            case canMoveDir.Right:
                return canMoveRight;
        }
        return true;
    }

    private void IfInputLR()
    {
        if (InputManager.Instance.Left(PlayerID))
        {
            if (canMoveLeft)
            {
                monoBase.Direction = new Vector3(-1, 0, 0);
                MoveByDirection(monoBase.Direction, monoBase.Speed);
                GetComponentInChildren<Animator>().SetFloat("Blend", 0.66f);
                GetComponentInChildren<Animator>().SetBool("Walking", true);
            }
        }
        else if (InputManager.Instance.Right(PlayerID))
        {
            if (canMoveRight)
            {
                monoBase.Direction = new Vector3(1, 0, 0);
                MoveByDirection(monoBase.Direction, monoBase.Speed);
                GetComponentInChildren<Animator>().SetFloat("Blend", 1f);
                GetComponentInChildren<Animator>().SetBool("Walking", true);
            }
        }
    }
    private void IfInputUD()
    {
        if (InputManager.Instance.Up(PlayerID))
        {
            if (canMoveUp)
            {
                monoBase.Direction = new Vector3(0, 1, 0);
                GetComponentInChildren<Animator>().SetFloat("Blend", 0.33f);
                GetComponentInChildren<Animator>().SetBool("Walking", true);
                MoveByDirection(monoBase.Direction, monoBase.Speed);
            }
        }
        else if (InputManager.Instance.Down(PlayerID))
        {
            if (canMoveDown)
            {
                monoBase.Direction = new Vector3(0, -1, 0);
                GetComponentInChildren<Animator>().SetFloat("Blend", 0.33f);
                GetComponentInChildren<Animator>().SetBool("Walking", true);
                MoveByDirection(monoBase.Direction, monoBase.Speed);
            }
        }
    }
    private void JudgeAnimDirect(Vector3 P)
    {
        if (Mathf.Abs(P.x) > Mathf.Abs(P.y))
        {
            if (P.x > 0)
            {
                GetComponentInChildren<Animator>().SetFloat("Blend", 1f);
            }
            else
            {
                GetComponentInChildren<Animator>().SetFloat("Blend", 0.66f);
            }
        }
        else
        {
            if (P.y > 0)
            {
                GetComponentInChildren<Animator>().SetFloat("Blend", 0f);
            }
            else
            {
                GetComponentInChildren<Animator>().SetFloat("Blend", 0.33f);
            }
        }
    }
    public override void UseSkill(Vector3 Direct,int SkillID, out bool ShootSuccess)
    {
        base.UseSkill(Direct, SkillID, out ShootSuccess);
        JudgeAnimDirect(Direct);
        GameMgr.Get<ISkillManager>().UseSkill(monoBase, monoBase.SkillList[SkillID], monoBase.Position, Direct, GetComponent<CircleCollider2D>().radius + 0.25f, monoBase.Attr,(InputManager.Instance.GetTarget(PlayerID)-monoBase.Position).magnitude);
    }


}